package com.sso.service.impl;

import com.common.utils.JsonUtil;
import com.common.utils.Md5Util;
import com.common.utils.UUIDUtil;
import com.sso.mapper.AdminMapper;
import com.sso.pojo.Admin;
import com.sso.pojo.AdminExample;
import com.sso.service.ssoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ssoServiceImpl implements ssoService {
    /**
     * 登录认证方法返回票据ticket
     *
     * @param admin
     * @return
     */

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${user.ticket}")
    private String userTicket;

    @Override
    public String login(Admin admin) {
        //判断参数合法性
        if (StringUtils.isEmpty(admin.getUserName().trim())) {
            System.out.println("用户名为空");
        }
        if (StringUtils.isEmpty(admin.getPassword().trim())) {
            System.out.println("密码为空");
        }
        //创建查询对象
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        //设置查询对象
        criteria.andUserNameEqualTo(admin.getUserName());
        //开始查询
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        //判断个数：只有列表存在一个admin才是正确
        if (adminList.size() == 0 || adminList.size() > 1) {
            System.out.println("用户不存在");
        }
        //取出第一个元素
        Admin admin1 = adminList.get(0);
        //验证密码
        if (!admin1.getPassword().equalsIgnoreCase(Md5Util.getMd5WithSalt(admin.getPassword(), admin1.getEcSalt()))) {
            System.out.println("用户名或密码错误");
        }
        //生成票据信息存入redis，页面借助cookie存储票据ticket
        ValueOperations<String, String> Valueoperations = redisTemplate.opsForValue();
        //生成id
        String ticket = UUIDUtil.getUUID();
        //设置30分钟过期
        Valueoperations.set(userTicket + ":" + ticket, JsonUtil.object2JsonStr(admin1), 30, TimeUnit.SECONDS);
        return ticket;
    }

    /**
     * 验证票据ticket返回用户信息
     *
     * @param ticket
     * @return
     */
    @Override
    public Admin validate(String ticket) {
        //如果票据信息为空：提示
        if (StringUtils.isEmpty(ticket)) {
            System.out.println("票据信息不存在");
            return null;
        }
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String adminJson = valueOperations.get(userTicket + ":" + ticket);
        //如果票据信息对应的数据不存在
        if (StringUtils.isEmpty(adminJson)) {
            System.out.println("票据对应的用户信息不存在");
        }
        return JsonUtil.jsonStr2Object(adminJson, Admin.class);
    }
}
